package com.ulife.category.module.screen;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.ulife.category.dao.CategoryDao;
import com.ulife.category.dao.dataobject.CategoryDo;
import com.ulife.category.module.vo.CategoryVo;
import com.ulife.common.ErrorMessage;

/**
 * 类目列表
 * 
 * @author Administrator
 */
public class Catelist {

	private static final Logger log = LoggerFactory.getLogger(Catelist.class);

	@Autowired
	private CategoryDao categoryDao;

	@Autowired
	private HttpServletRequest request;

	public void execute(Context context, Navigator nav) {
		context.put("module", "cate");
		String catIdStr = request.getParameter("id");
		Long catId = null;
		if (StringUtils.isNotBlank(catIdStr) && StringUtils.isNumeric(catIdStr)) {
			catId = Long.parseLong(catIdStr);
			CategoryDo parentCate;
			try {
				parentCate = categoryDao.queryCategoryById(catId);
				if (parentCate == null) {
					context.put("msg", ErrorMessage.NOT_EXIST_CATEGORY);
					nav.forwardTo("message");
					return;
				}
				context.put("parentcat", parentCate);
			} catch (Exception e) {
				log.error("queryCategoryById error! ", e);
			}
		}

		List<CategoryVo> catesForView = new ArrayList<CategoryVo>();
		try {
			List<CategoryDo> cates = categoryDao.queryAllEnableCategoryByParentId(catId);
			for (CategoryDo categoryDo : cates) {
				CategoryVo cateVo = new CategoryVo();
				BeanUtils.copyProperties(categoryDo, cateVo);
				if (categoryDo.getcParentid() != null && categoryDo.getcParentid() > 0L) {
					CategoryDo pCate = categoryDao.queryCategoryById(categoryDo.getcParentid());
					if (pCate != null) {
						cateVo.setParentCateName(pCate.getcName());
					} else {
						cateVo.setParentCateName("[不存在]");
					}
				} else {
					cateVo.setParentCateName("[无]");
				}
				catesForView.add(cateVo);
			}
			
		} catch (Exception e) {
			log.error("show catelist error! ", e);
		}
		context.put("categorys", catesForView);
	}

}
